package com.common.baselibrary.rxjava2.utils;

import android.util.Log;

import com.common.baselibrary.util.Logger;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/*表单提交*/

public class JSONReqParams {

    private HashMap<String, Object> paramMap;

    private JSONReqParams() {
        paramMap = new HashMap<>();
    }

    public static JSONReqParams construct() {
        return new JSONReqParams();
    }

    public JSONReqParams put(String key, Object value) {
        paramMap.put(key, value);
        Log.e("bst===", "提交的参数为==="+new Gson().toJson(paramMap));
        return this;
    }

    public HashMap<String, Object> getMap() {
        return paramMap;
    }

    public RequestBody buildRequestBody() {
        String json = generateJSONObject(paramMap).toString();
        Logger.e(json);
        return RequestBody.create(json, MediaType.parse("application/json"));
    }

    private JSONObject generateJSONObject(HashMap<String, Object> dataMap) {
        JSONObject params = new JSONObject();
        try {
            if (dataMap != null) {
                Set<Map.Entry<String, Object>> entries = dataMap.entrySet();
                for (Map.Entry<String, Object> entry : entries) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (value instanceof HashMap) {
                        params.put(key, generateJSONObject((HashMap<String, Object>) value));
                    } else if (value instanceof List) {
                        JSONArray array = new JSONArray(((List) value));
                        params.put(key, array);
                    } else {
                        params.put(key, value);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }
}
